package com.my.springcloud.controller;

import com.my.springcloud.config.ApplicationContextConfig;
import com.my.springcloud.entities.CommonResult;
import com.my.springcloud.entities.Payment;
import com.my.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private ApplicationContextConfig applicationContextConfig;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("端口号：{}，插入payment：{}，结果：{}", applicationContextConfig.getPort(), payment, result);
        if (result > 0) {
            return new CommonResult(result);
        } else {
            return new CommonResult(500, "error", result);
        }
    }

    @GetMapping("/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            log.info("端口号：{}，查询成功payment:{}", applicationContextConfig.getPort(), payment);
            return new CommonResult(200, "端口号："+applicationContextConfig.getPort()+"，查询成功", payment);
        } else {
            log.info("端口号：{}，查询失败paymentId:{}", applicationContextConfig.getPort(), id);
            return new CommonResult(500, "端口号："+applicationContextConfig.getPort()+"，查询失败");
        }
    }

    @GetMapping("/discovery")
    public Object discovery(){
        List<String> servicesList =  discoveryClient.getServices();
        for (String service:servicesList ) {
            log.info("发现服务:{}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance:instances ) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return discoveryClient;
    }
}
